#define _CRT_SECURE_NO_WARNINGS 1
#include "heap.h"
void HeapInit(Heap* php)
{
	assert(php);
	php->a = (HPDataType*)malloc(sizeof(HPDataType) * 4);
	if (php->a == NULL)
	{
		perror("Malloc fail");
		return;
	}
	php->size = 0;
	php->capacity = 4;
}

void HeapDestory(Heap* hp)
{
	assert(hp);
	free(hp->a);
	hp->size = 0;
	hp->capacity = 0;
}

void swap(HPDataType* a, HPDataType* b)
{
	int tem = 0;
	tem = *a;
	*a = *b;
	*b = tem;
}
void Adjustup(HPDataType* a, HPDataType child)
{
	assert(a);
	HPDataType parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[parent])
		{
			swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
			break;
	}
}

void AdjustDown(HPDataType* a, int n, int parent)
{
	assert(a);
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child] < a[child + 1])
		{
			child = child + 1;
		}
		if (a[parent] < a[child])
		{
			swap(&a[parent], &a[child]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
			break;
	}
}
void HeapPush(Heap* hp, HPDataType x)
{
	assert(hp);
	if (hp->size == hp->capacity)
	{
		HPDataType* tem = (HPDataType*)realloc(hp->a, sizeof(HPDataType) * hp->capacity * 2);
		if (tem == NULL)
		{
			perror("Realloc fail");
			return;
		}
			hp->a = tem;
			hp->capacity *= 2;
	}
	hp->a[hp->size++] = x;
	Adjustup(hp->a,hp->size - 1);
}

void HeapPop(Heap* hp)
{
	assert(hp);
	assert(!HeapEmpty(hp));
	swap(&hp->a[0], &hp->a[hp->size - 1]);
	hp->size--;
	AdjustDown(hp->a, hp->size,0);
}

bool HeapEmpty(Heap* hp)
{
	assert(hp);
	return hp->size == 0;
}

HPDataType HeapPop(Heap* hp)
{
	assert(hp);
	return hp->a[0];
}

int HeapSize(Heap* hp)
{
	assert(hp);
	return hp->size;
}